package com.hulk.summary.wrapper;

import com.hulk.summary.SummaryProperties;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.ServletOutputStream;
import javax.servlet.WriteListener;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.*;

/**
 * response包装类
 *
 * @author hulk
 * @see https://blog.csdn.net/qq_33206732/article/details/78623042
 * @see https://www.cnblogs.com/linma/p/7845124.html
 */
@Slf4j
public class ResponseWrapper extends HttpServletResponseWrapper {

    private ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    private HttpServletResponse response;
    private PrintWriter pwrite;

    public ResponseWrapper(HttpServletResponse response) {
        super(response);
        this.response = response;
    }

    @Override
    public ServletOutputStream getOutputStream()  {
        return new SummaryServletOutputStream(bytes); // 将数据写到 byte 中
    }

    /**
     * 重写父类的 getWriter() 方法，将响应数据缓存在 PrintWriter 中
     */
    @Override
    public PrintWriter getWriter()  {
        pwrite = new PrintWriter(new OutputStreamWriter(bytes, StandardCharsets.UTF_8));
        return pwrite;
    }

    /**
     * 获取缓存在 PrintWriter 中的响应数据
     * @return
     */
    @SneakyThrows
    public byte[] getBytes() {
        if(null != pwrite) {
            pwrite.close();
            return bytes.toByteArray();
        }
        if(null != bytes) {
           bytes.flush();
        }
        return bytes.toByteArray();
    }

    class SummaryServletOutputStream extends ServletOutputStream {

        private ByteArrayOutputStream ostream ;

        public SummaryServletOutputStream(ByteArrayOutputStream ostream) {
            this.ostream = ostream;
        }

        @Override
        public void write(int b)  {
            ostream.write(b); // 将数据写到 stream　中
        }

        @Override
        public boolean isReady() {
            return false;
        }

        @Override
        public void setWriteListener(WriteListener writeListener) {

        }
    }

    /**
     * 获取签名字符串
     * @param parameters 签名Map
     * @return 签名字符串
     */

    //TODO 如果json中包含list需要测试
    public static String createSignature(SortedMap<String, Object> parameters, SummaryProperties p) {
        StringBuilder sb = new StringBuilder();
        Set<Map.Entry<String,Object>> es = parameters.entrySet();
        for (Map.Entry<String,Object> e : es) {
            String k =  e.getKey();
            String v = (e.getValue() == null ||
                    e.getValue() instanceof List ||
                    e.getValue().getClass().isArray()
            ) ? "" : e.getValue().toString();
            //空值不传递，不参与签名组串
            if (null != v && !"".equals(v) && !Objects.equals(k,p.getSummaryName())) {
                sb.append(k).append("=").append(v).append("&");
            }
        }
        log.debug(sb.toString());
        String name =  String.valueOf(parameters.get(p.getName()));
        String mval =  p.getSafes().get(name);
        //排序后的字符串
        return sb.append(mval).toString();
    }

}